package com.ruoyi.common.utils.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class NetworkUtils {
    public static List<String> readAllIPs() {
        List<String> ipList = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                // 过滤掉Loopback, Virtual和PointToPoint等不常用的接口类型
                if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    // 过滤掉回环地址和IPv6的链路本地地址（fe80::/10）
                    if (address instanceof java.net.Inet4Address && !address.isLoopbackAddress() && !address.getHostAddress().contains(":")) {
                        System.out.println("Interface: " + networkInterface.getName() + " IP Address: " + address.getHostAddress());
                        ipList.add(address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList;
    }

    public static void main(String[] args) {
        readAllIPs();
    }
}